package com.emapp.lccode.utils

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.amap.api.maps.model.LatLng
import com.emapp.lccode.R
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.CommTypeKt
import com.emapp.lccode.bean.Lu
import com.emapp.lccode.bean.MapJsonDeserialize2
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastParams
import com.hjq.toast.Toaster
import com.hjq.toast.style.CustomToastStyle
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.style.PictureSelectorStyle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import java.lang.reflect.Field
import java.net.URL
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 描述　:一些常用的方法
 */


val gson: Gson by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { Gson() }

inline fun <reified T> String.toEntity(): T? {
    val type = object : TypeToken<T>() {}
    return try {
        gson.fromJson(this, type.type)
    } catch (e: Exception) {
        null
    }
}

inline fun <reified T> String.toArrayEntity(): ArrayList<T>? {
    val type = object : TypeToken<ArrayList<T>>() {}
    return try {
        gson.fromJson(this, type.type)
    } catch (e: Exception) {
        null
    }

}

fun Any?.toJsonStr(): String {
    return gson.toJson(this)
}

fun Any?.toast() {
    Toaster.show(this)
}
fun showWarn(v: String) {
    val params = ToastParams()
    params.text = v
    params.style = CustomToastStyle(R.layout.toast_warn)
    Toaster.show(params)
}
fun showInfo(v: String) {
    val params = ToastParams()
    params.text = v
    params.style = CustomToastStyle(R.layout.toast_info)
    Toaster.show(params)
}
fun showSuccess(v: String) {
    val params = ToastParams()
    params.text = v
    params.style = CustomToastStyle(R.layout.toast_success)
    Toaster.show(params)
}
fun showError(v: String) {
    val params = ToastParams()
    params.text = v
    params.style = CustomToastStyle(R.layout.toast_error)
    Toaster.show(params)
}
/**
 * 用反射来通过字符串匹配对象的属性名
 */
//fun getValueByPropertyName(obj: Any, propertyName: String): Any? {
//    val kClass = obj::class
//    val property = kClass.memberProperties.firstOrNull { it.name == propertyName }
//    return property?.get(obj)
//}
/**
 * 用反射来通过字符串匹配对象的属性名
 */
fun getValueByPropertyName(obj: Any, propertyName: String): Any? {
    return try {
        val field: Field = obj.javaClass.getDeclaredField(propertyName)
        field.isAccessible = true
        val propertyValue = field.get(obj)
        propertyValue?.let {
            // 进行类型转换
            return when (it) {
                is String -> {
                    if (it.toString() == "null") "" else it
                } // 将属性值转换为 String 类型
                is Int -> {
                    it
                }  // 将属性值转换为 Int 类型
                else -> "" // 不支持的类型，返回 null 或其他默认值
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
        return ""
    }
}

/**
 * 关闭键盘
 */
fun EditText.hideKeyboard() {
    val imm = BaseApplication.instance
        .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(
        this.windowToken,
        InputMethodManager.HIDE_IMPLICIT_ONLY
    )
}

/**
 * 打开键盘
 */
fun EditText.openKeyboard() {
    this.apply {
        isFocusable = true
        isFocusableInTouchMode = true
        requestFocus()
    }
    val inputManager =
        BaseApplication.instance
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.showSoftInput(this, 0)
}

/**
 * 关闭键盘焦点
 */
fun Activity.hideOffKeyboard() {
    val imm = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (imm.isActive && this.currentFocus != null) {
        if (this.currentFocus?.windowToken != null) {
            imm.hideSoftInputFromWindow(
                this.currentFocus?.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}

fun toStartActivity(@NonNull clz: Class<*>) {
    val intent = Intent(BaseApplication.instance, clz)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    BaseApplication.instance.startActivity(intent)
}

fun toStartActivity(@NonNull clz: Class<*>, @NonNull bundle: Bundle) {
    val intent = Intent(BaseApplication.instance, clz)
    intent.apply {
        putExtras(bundle)
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
    }
    BaseApplication.instance.startActivity(intent)
}

fun toStartActivity(
    activity: Activity,
    @NonNull clz: Class<*>,
    code: Int,
    @NonNull bundle: Bundle
) {
    activity.startActivityForResult(
        Intent(BaseApplication.instance, clz).putExtras(bundle),
        code
    )
}

fun toStartActivity(
    fragment: Fragment,
    @NonNull clz: Class<*>,
    code: Int,
    @NonNull bundle: Bundle
) {
    fragment.startActivityForResult(
        Intent(BaseApplication.instance, clz).putExtras(bundle),
        code
    )
}

fun toStartActivity(activity: Activity, @NonNull intent: Intent, code: Int) {
    activity.startActivityForResult(intent, code)
}

fun toStartActivity(
    @NonNull type: Any,
    @NonNull clz: Class<*>,
    code: Int,
    @NonNull bundle: Bundle
) {
    if (type is Activity) {
        toStartActivity(type, clz, code, bundle)
    } else if (type is Fragment) {
        toStartActivity(type, clz, code, bundle)
    }
}

/**
 * 隐藏状态栏
 */
fun hideStatusBar(activity: Activity) {
    val attrs = activity.window.attributes
    attrs.flags = attrs.flags or WindowManager.LayoutParams.FLAG_FULLSCREEN
    activity.window.attributes = attrs
}

/**
 * 显示状态栏
 */
fun showStatusBar(activity: Activity) {
    val attrs = activity.window.attributes
    attrs.flags = attrs.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN.inv()
    activity.window.attributes = attrs
}

/**
 * 横竖屏
 */
fun isLandscape(context: Context) =
    context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE

/**
 * 应用商店
 */
fun gotoStore() {
    val uri =
        Uri.parse("market://details?id=" + BaseApplication.instance.packageName)
    val goToMarket = Intent(Intent.ACTION_VIEW, uri)
    try {
        goToMarket.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        BaseApplication.instance.startActivity(goToMarket)
    } catch (ignored: ActivityNotFoundException) {
    }
}

fun getIconByName(work_type: String, name: String): Int {
    when (work_type) {
        "1" -> {//田
            return R.drawable.map_tian
        }

        "2" -> {//土
            return R.drawable.map_tu
        }

        "3" -> {//水
            return when {
                name.contains("井房") ->
                    R.drawable.map_fang

                name.contains("井") ->
                    R.drawable.map_jing

                name.contains("坝") ->
                    R.drawable.map_ba

                name.contains("雨") ->
                    R.drawable.map_yu

                name.contains("泵") ->
                    R.drawable.map_beng

                name.contains("闸") ->
                    R.drawable.map_zha

                name.contains("渠") ->
                    R.drawable.map_qu

                name.contains("虹吸") ->
                    R.drawable.map_dao

                name.contains("桥") ->
                    R.drawable.map_qiao

                name.contains("涵洞") ->
                    R.drawable.map_handong

                name.contains("跌水") ->
                    R.drawable.map_die

                name.contains("渡") ->
                    R.drawable.map_du

                name.contains("灌") ->
                    R.drawable.map_shui

                name.contains("公示牌") ->
                    R.drawable.map_pai

                name.contains("防") ->
                    R.drawable.map_fanghu

                name.contains("警") ->
                    R.drawable.map_jingcha

                name.contains("计量") ->
                    R.drawable.map_liang

                else ->
                    R.drawable.map_shui
            }
        }

        "4" -> {//路
            return R.drawable.map_lu
        }

        "5" -> {//林
            return when {
                name.contains("岸坡") ->
                    R.drawable.map_an

                name.contains("沟道") ->
                    R.drawable.map_gou

                name.contains("坡面") ->
                    R.drawable.map_po

                else ->
                    R.drawable.map_lin
            }
        }

        "6" -> {//电
            return when {
                name.contains("变压") ->
                    R.drawable.map_bianya

                name.contains("配") ->
                    R.drawable.map_pei

                name.contains("电杆") ->
                    R.drawable.map_gan

                else ->
                    R.drawable.map_dian
            }
        }

        "7" -> {//技
            return when {
                name.contains("气象") ->
                    R.drawable.map_qiti

                name.contains("仪器") ->
                    R.drawable.map_yiqi

                name.contains("耕地") ->
                    R.drawable.map_gengdi

                name.contains("灯") ->
                    R.drawable.map_deng

                name.contains("监") ->
                    R.drawable.map_jiankong

                else ->
                    R.drawable.map_ji
            }
        }

        else -> {//其他
            return when {
                name.contains("电") ->
                    R.drawable.map_dian

                name.contains("水") ->
                    R.drawable.map_shui

                name.contains("田") ->
                    R.drawable.map_tian

                name.contains("林") ->
                    R.drawable.map_lin

                name.contains("路") ->
                    R.drawable.map_lu

                name.contains("土") ->
                    R.drawable.map_tu

                name.contains("技") ->
                    R.drawable.map_ji

                name.contains("公示牌") ->
                    R.drawable.map_pai

                name.contains("防") ->
                    R.drawable.map_fanghu

                name.contains("警") ->
                    R.drawable.map_jingcha

                name.contains("计量") ->
                    R.drawable.map_liang

                else ->
                    R.drawable.map_qi2
            }
        }

//        else -> return R.drawable.map_qi2
    }
}

fun getIconByNameState(work_type: String, name: String, state: String): Int {
    when (work_type) {
        "1" -> {//田
            when (state) {
                "1" -> return R.drawable.map_tian
                "2" -> return R.drawable.map_tian
                "3" -> return R.drawable.map_tian
                else -> return R.drawable.map_tian
            }

        }

        "2" -> {//土
            when (state) {
                "1" -> return R.drawable.map_tu
                "2" -> return R.drawable.map_tu
                "3" -> return R.drawable.map_tu
                else -> return R.drawable.map_tu
            }
        }

        "3" -> {//水
            return when {
                name.contains("井房") -> {
                    when (state) {
                        "1" -> return R.drawable.map_jingfang_1
                        "2" -> return R.drawable.map_jingfang_2
                        "3" -> return R.drawable.map_jingfang_3
                        else -> return R.drawable.map_jingfang_1
                    }
                }

                name.contains("井") -> {
                    when (state) {
                        "1" -> return R.drawable.map_jing_1
                        "2" -> return R.drawable.map_jing_2
                        "3" -> return R.drawable.map_jing_3
                        else -> return R.drawable.map_jing_1
                    }
                }

                name.contains("坝") -> {
                    when (state) {
                        "1" -> return R.drawable.map_ba_1
                        "2" -> return R.drawable.map_ba_2
                        "3" -> return R.drawable.map_ba_3
                        else -> return R.drawable.map_ba_1
                    }
                }

                name.contains("雨") -> {
                    when (state) {
                        "1" -> return R.drawable.map_yu_1
                        "2" -> return R.drawable.map_yu_2
                        "3" -> return R.drawable.map_yu_3
                        else -> return R.drawable.map_yu_1
                    }
                }

                name.contains("泵") -> {
                    when (state) {
                        "1" -> return R.drawable.map_beng_1
                        "2" -> return R.drawable.map_beng_2
                        "3" -> return R.drawable.map_beng_3
                        else -> return R.drawable.map_beng_1
                    }
                }

                name.contains("闸") -> {
                    when (state) {
                        "1" -> return R.drawable.map_zha_1
                        "2" -> return R.drawable.map_zha_2
                        "3" -> return R.drawable.map_zha_3
                        else -> return R.drawable.map_zha
                    }
                }

                name.contains("渠") ->
                    when (state) {
                        "1" -> return R.drawable.map_qu
                        "2" -> return R.drawable.map_qu
                        "3" -> return R.drawable.map_qu
                        else -> return R.drawable.map_qu
                    }

                name.contains("虹吸") -> {
                    when (state) {
                        "1" -> return R.drawable.map_dao_1
                        "2" -> return R.drawable.map_dao_2
                        "3" -> return R.drawable.map_dao_3
                        else -> return R.drawable.map_dao
                    }
                }

                name.contains("桥") -> {
                    when (state) {
                        "1" -> return R.drawable.map_qiao_1
                        "2" -> return R.drawable.map_qiao_2
                        "3" -> return R.drawable.map_qiao_3
                        else -> return R.drawable.map_qiao
                    }
                }

                name.contains("涵洞") -> {
                    when (state) {
                        "1" -> return R.drawable.map_han_1
                        "2" -> return R.drawable.map_han_2
                        "3" -> return R.drawable.map_han_3
                        else -> return R.drawable.map_handong
                    }
                }

                name.contains("跌水") -> {
                    when (state) {
                        "1" -> return R.drawable.map_die_1
                        "2" -> return R.drawable.map_die_2
                        "3" -> return R.drawable.map_die_3
                        else -> return R.drawable.map_die
                    }
                }

                name.contains("渡") -> {
                    when (state) {
                        "1" -> return R.drawable.map_du_1
                        "2" -> return R.drawable.map_du_2
                        "3" -> return R.drawable.map_du_3
                        else -> return R.drawable.map_du
                    }
                }

                name.contains("灌") -> {
                    when (state) {
                        "1" -> return R.drawable.map_guan_1
                        "2" -> return R.drawable.map_guan_2
                        "3" -> return R.drawable.map_guan_3
                        else -> return R.drawable.map_guan_0
                    }
                }

                name.contains("公示牌") -> {
                    when (state) {
                        "1" -> return R.drawable.map_pai_1
                        "2" -> return R.drawable.map_pai_2
                        "3" -> return R.drawable.map_pai_3
                        else -> return R.drawable.map_pai
                    }
                }

                name.contains("防") -> {
                    when (state) {
                        "1" -> return R.drawable.map_fang_1
                        "2" -> return R.drawable.map_fang_2
                        "3" -> return R.drawable.map_fang_3
                        else -> return R.drawable.map_fanghu
                    }
                }

                name.contains("警") -> {
                    when (state) {
                        "1" -> return R.drawable.map_police_1
                        "2" -> return R.drawable.map_police_2
                        "3" -> return R.drawable.map_police_3
                        else -> return R.drawable.map_jingcha
                    }
                }

                name.contains("计量") -> {
                    when (state) {
                        "1" -> return R.drawable.map_liang_1
                        "2" -> return R.drawable.map_liang_2
                        "3" -> return R.drawable.map_liang_3
                        else -> return R.drawable.map_liang
                    }
                }

                else -> {
                    R.drawable.map_shui
                }

            }
        }

        "4" -> {//路
            return R.drawable.map_lu
        }

        "5" -> {//林
            return when {
                name.contains("岸坡") ->
                    R.drawable.map_an

                name.contains("沟道") ->
                    R.drawable.map_gou

                name.contains("坡面") ->
                    R.drawable.map_po

                else ->
                    R.drawable.map_lin
            }
        }

        "6" -> {//电
            return when {
                name.contains("变压") -> {
                    when (state) {
                        "1" -> return R.drawable.map_bian_1
                        "2" -> return R.drawable.map_bian_2
                        "3" -> return R.drawable.map_bian_3
                        else -> return R.drawable.map_bianya
                    }
                }

                name.contains("配") -> {
                    when (state) {
                        "1" -> return R.drawable.map_pei_1
                        "2" -> return R.drawable.map_pei_2
                        "3" -> return R.drawable.map_pei_3
                        else -> return R.drawable.map_pei
                    }
                }

                name.contains("电杆") ->
                    R.drawable.map_gan

                else ->
                    R.drawable.map_dian
            }
        }

        "7" -> {//技
            return when {
                name.contains("气象") -> {
                    when (state) {
                        "1" -> return R.drawable.map_qi_1
                        "2" -> return R.drawable.map_qi_2
                        "3" -> return R.drawable.map_qi_3
                        else -> return R.drawable.map_qiti
                    }
                }

                name.contains("仪器") ->
                    R.drawable.map_yiqi

                name.contains("耕地") -> {
                    when (state) {
                        "1" -> return R.drawable.map_geng_1
                        "2" -> return R.drawable.map_geng_2
                        "3" -> return R.drawable.map_geng_3
                        else -> return R.drawable.map_gengdi
                    }
                }

                name.contains("灯") -> {
                    when (state) {
                        "1" -> return R.drawable.map_deng_1
                        "2" -> return R.drawable.map_deng_2
                        "3" -> return R.drawable.map_deng_3
                        else -> return R.drawable.map_deng
                    }
                }

                name.contains("监") -> {
                    when (state) {
                        "1" -> return R.drawable.map_jian_1
                        "2" -> return R.drawable.map_jian_2
                        "3" -> return R.drawable.map_jian_3
                        else -> return R.drawable.map_jiankong
                    }
                }

                else ->
                    R.drawable.map_ji
            }
        }

        else -> {//其他
            return when {
                name.contains("电") ->
                    R.drawable.map_dian

                name.contains("水") ->
                    R.drawable.map_shui

                name.contains("田") ->
                    R.drawable.map_tian

                name.contains("林") ->
                    R.drawable.map_lin

                name.contains("路") ->
                    R.drawable.map_lu

                name.contains("土") ->
                    R.drawable.map_tu

                name.contains("技") ->
                    R.drawable.map_ji

                name.contains("公示牌") -> {
                    when (state) {
                        "1" -> return R.drawable.map_pai_1
                        "2" -> return R.drawable.map_pai_2
                        "3" -> return R.drawable.map_pai_3
                        else -> return R.drawable.map_pai
                    }
                }

                name.contains("防") -> {
                    when (state) {
                        "1" -> return R.drawable.map_fang_1
                        "2" -> return R.drawable.map_fang_2
                        "3" -> return R.drawable.map_fang_3
                        else -> return R.drawable.map_fanghu
                    }
                }

                name.contains("警") -> {
                    when (state) {
                        "1" -> return R.drawable.map_police_1
                        "2" -> return R.drawable.map_police_2
                        "3" -> return R.drawable.map_police_3
                        else -> return R.drawable.map_jingcha
                    }
                }

                name.contains("计量") -> {
                    when (state) {
                        "1" -> return R.drawable.map_liang_1
                        "2" -> return R.drawable.map_liang_2
                        "3" -> return R.drawable.map_liang_3
                        else -> return R.drawable.map_liang
                    }
                }

                name.contains("界") -> {
                    when (state) {
                        "1" -> return R.drawable.map_jie_1
                        "2" -> return R.drawable.map_jie_2
                        "3" -> return R.drawable.map_jie_3
                        else -> return R.drawable.map_jie_0
                    }
                }

                name.contains("其他工程") -> {
                    when (state) {
                        "1" -> return R.drawable.map_chai_1
                        "2" -> return R.drawable.map_chai_2
                        "3" -> return R.drawable.map_chai_3
                        else -> return R.drawable.map_chai_0
                    }
                }

                else ->
                    R.drawable.map_qi2
            }
        }

//        else -> return R.drawable.map_qi2
    }
}

fun getLuByNameState(work_type: String, name: String, state: String): Int {
    when (work_type) {
        "1" -> {//田
            return R.drawable.lu_nongtian
        }

        "2" -> {//土
            return R.drawable.lu_nongtian
        }

        "3" -> {//水
            return when {

                name.contains("沟渠") -> {
                    return R.drawable.lu_gouqu
                }
                name.contains("暗管")||
                name.contains("暗渠") -> {
                    return R.drawable.lu_anqu
                }
                name.contains("明沟")||
                name.contains("明渠") -> {
                    return R.drawable.lu_mingqu
                }

                else -> {
                    R.drawable.lu_paishui
                }

            }
        }

        "4" -> {//路
            return when {
                name.contains("机耕") -> {
                    R.drawable.lu_jigeng
                }

                name.contains("生产") -> {
                    R.drawable.lu_shengchan
                }

                name.contains("农田") -> {
                    R.drawable.lu_nongtian
                }

                else -> {
                    R.drawable.lu_qita
                }

            }
        }

        "5" -> {//林
            return  R.drawable.lu_qita
        }

        "6" -> {//电
            return when {
                name.contains("高压") -> {
                    R.drawable.lu_gaoya
                }

                name.contains("低压") -> {
                    R.drawable.lu_diya
                }

                else ->
                    R.drawable.lu_diya
            }
        }

        "7" -> {//技
            return when {

                else ->
                    return  R.drawable.lu_qita
            }
        }

        else -> {//其他
            return  R.drawable.lu_qita
        }

//        else -> return R.drawable.map_qi2
    }
}

val statesList = listOf<String>("未开工", "建设中")
val statesListall = listOf<String>("未开工", "建设中", "已竣工", "全部")
val formTypes: ArrayList<CommTypeKt> = arrayListOf(
    CommTypeKt("0", "内部巡检"),
    CommTypeKt("1", "巡管员"),
    CommTypeKt("2", "投诉报修"),
    CommTypeKt("3", "电话报修")
)

val approveTypes: ArrayList<CommTypeKt> = arrayListOf(
    CommTypeKt("1", "内部工单"),
    CommTypeKt("2", "保险工单")
)
var years: ArrayList<String> =
    arrayListOf("2018", "2019", "2020", "2021", "2022", "2023", "2024", "全部")

fun getluJsonString(latLngs: ArrayList<LatLng>): String {
    val coordinates: ArrayList<ArrayList<Double>> = arrayListOf()
    latLngs.forEach {
        val g = MapAppUtil.gcj02_To_Gps84(it.latitude, it.longitude)
        val wgs_lat = g[0]
        val wgs_lng = g[1]
        val d: ArrayList<Double> = arrayListOf(wgs_lng, wgs_lat)
        coordinates.add(d)
    }
    val lu = Lu()
    val features = Lu.Features()
    val geometry = Lu.Features.Geometry()
    geometry.coordinates = coordinates
    features.geometry = geometry
    lu.features.add(features)
    val gson = GsonBuilder()
        .registerTypeAdapter(Lu.Features.Geometry::class.java, MapJsonDeserialize2())
        .create()
    return gson.toJson(lu)
}

fun scaleBitmap(bitmap: Bitmap, scale: Float): Bitmap {
    val matrix = Matrix()
    matrix.postScale(scale, scale)
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}

/**
 * 创建自定义输出目录
 *
 * @return
 */
fun getSandboxMarkDir(): String {
    val externalFilesDir = BaseApplication.instance.getExternalFilesDir("")
    val customFile = File(externalFilesDir!!.absolutePath, "Mark")
    if (!customFile.exists()) {
        customFile.mkdirs()
    }
    return customFile.absolutePath + File.separator
}

/**
 * 字符串相等
 */
fun isEqualStr(value: String?, defaultValue: String?) =
    if (value.isNullOrEmpty() || defaultValue.isNullOrEmpty()) false else TextUtils.equals(
        value,
        defaultValue
    )

/**
 * Int类型相等
 *
 */
fun isEqualIntExt(value: Int, defaultValue: Int) = value == defaultValue

fun getDrawableExt(id: Int): Drawable? =
    ContextCompat.getDrawable(BaseApplication.instance, id)

fun getColorExt(id: Int): Int = ContextCompat.getColor(BaseApplication.instance, id)

fun getStringExt(id: Int) = BaseApplication.instance.resources.getString(id)

fun getStringArrayExt(id: Int): Array<String> =
    BaseApplication.instance.resources.getStringArray(id)

fun getIntArrayExt(id: Int) = BaseApplication.instance.resources.getIntArray(id)

fun getDimensionExt(id: Int) = BaseApplication.instance.resources.getDimension(id)
fun openCamera(
    contect: Context,
    name: String,
    data: ArrayList<LocalMedia>,
    launcherResult: ActivityResultLauncher<Intent>
) {
    PictureSelector.create(contect)
        .openCamera(SelectMimeType.ofImage())
        .setCompressEngine(ImageFileCompressEngine())
        .setSandboxFileEngine(MeSandboxFileEngine())
        .setAddBitmapWatermarkListener(MeBitmapWatermarkEventListener(getSandboxMarkDir(),name))
        .setSelectedData(data).also {
            it.forResultActivity(launcherResult)
        }
}

fun openGallery(
    contect: Context,
    data: ArrayList<LocalMedia>,
    launcherResult: ActivityResultLauncher<Intent>
) {
    PictureSelector.create(contect)
        .openGallery(SelectMimeType.ofImage())
        .setSelectorUIStyle(PictureSelectorStyle())
        .setImageEngine(GlideEngine.createGlideEngine()) //.setCropEngine(getCropFileEngine())
        .setCompressEngine(ImageFileCompressEngine())
        .setSandboxFileEngine(MeSandboxFileEngine())
        .setSelectionMode(SelectModeConfig.MULTIPLE)
        // .setAddBitmapWatermarkListener(MeBitmapWatermarkEventListener(getSandboxMarkDir(),getWater()))
        .isDisplayCamera(true)
        .setMaxSelectNum(BaseConfig.selectMaxImage)
        .setSelectedData(data).also {
            it.forResult(launcherResult)
        }
}

suspend fun downloadAndSaveImage(context: Context, imageUrl: String) {
    withContext(Dispatchers.IO) {
        try {
            val imageBitmap: Bitmap = BitmapFactory.decodeStream(URL(imageUrl).openStream())

            // 创建保存图片的文件
            val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "IMG_$timestamp.jpg"
            val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            val imageFile = File(storageDir, fileName)

            // 保存图片到文件
            val outputStream: OutputStream = FileOutputStream(imageFile)
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream.flush()
            outputStream.close()

            // 更新相册
            updateGallery(context, imageFile)

            withContext(Dispatchers.Main) {
                // 下载保存成功的提示
                Toast.makeText(context, "图片已保存到相册", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            withContext(Dispatchers.Main) {
                // 下载保存失败的提示
                Toast.makeText(context, "保存图片失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

private fun updateGallery(context: Context, imageFile: File) {
    // 插入图片到相册
    val values = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.name)
        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
        put(MediaStore.Images.Media.DATA, imageFile.absolutePath)
    }

    context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
}
fun isInternetConnected(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork ?: return false
        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
                capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    } else {
        @Suppress("DEPRECATION")
        return try {
            connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnected
        } catch (e: Exception) {
            false
        }
    }
}
/**
 * 倒计时扩展函数
 * @param total Int 倒计时的秒数 比如 10秒
 * @param onTick Function1<Int, Unit> 倒计时一次回调函数
 * @param onFinish Function0<Unit> 倒计时结束回调函数
 * @param scope CoroutineScope 作用域
 * @return Job
 *
 *
 *  var o= countDownCoroutines(10,onTick={re->
log_e("onTick-----"+re)
}, onFinish = {
log_e("onFinish-----")
})

var o= countDownCoroutines(10,{re->
log_e("onTick-----$re")
}, { log_e("onFinish-----") })
 */
fun countDownCoroutines(
    total: Int,
    onTick: (Int) -> Unit,
    onFinish: () -> Unit,
    scope: CoroutineScope = GlobalScope
): Job {
    return flow {
        for (i in total downTo 1) {
            emit(i)
            delay(1000)
        }
    }.flowOn(Dispatchers.Default)
        .onCompletion { onFinish.invoke() }
        .onEach { onTick.invoke(it) }
        .flowOn(Dispatchers.Main)
        .launchIn(scope)

}